Getting Started with Duende IdentityServer6
Table of Contents
Dependencies
- .Net 7 SDK
Installation
Setup NuGet Source. Run these commands from a terminal:
dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org
dotnet nuget enable source nuget.orgInstall the IdentityServer templates. You will use these to start your new project.
dotnet new install Duende.IdentityServer.TemplatesCreate a New Identity Server
Create a folder for your project. Create another folder inside named
src.Create a new .net solution in the project root.
dotnet new sln -n project_nameCreate a “empty template” in the
srcfolder and add the project to the solution.dotnet new isempty -n IdentityServer cd .. dotnet sln add ./src/IdentityServer/IdentityServer.csprojCreate a scope for clients to access the API. In the file at
src/IdentityServer/Config.csadd in the ApiScopes property:using Duende.IdentityServer; // ... public static IEnumerable<ApiScope> ApiScopes => new List<ApiScope> { new ApiScope(name: "api1", displayName: "MyAPI") };Now we can configure clients to access the Identity Server and API. See the following for each client type:
Configuring an API Project
At the src level of the API, add JWT Bearer Authentication:
dotnet add ./api_project_directory/api.csproj package Microsoft.AspNetCore.Authentication.JwtBearerIn the Program.cs file of the API, add the JWT Bearer authentication services to the Service Collection:
using Microsoft.IdentityModel.Tokens;
// ...
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "URI of IdentityServer";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});In the same file, add the authentication middleware immediately before authorization:
app.UseAuthentication();
app.UseAuthorization();Add a new class called IdentityController in the API controllers directory:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Route("identity")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}Test the configuration by running the API project, and navigating to the identity controller at "api_url/identity". It should return a 401 status code, which means it requires a credential and is protected by the IdentityServer.
Add an Authorization Policy to the API to check for the proper scope in the access token. In Program.cs of the API:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1");
});
});Map the policy to the controllers in the same file:
app.MapControllers().RequireAuthorization("ApiScope");Notes
- More detailed information about Duende can be found here
- Edit
src/IdentityServer/Properties/launchSettings.jsonto change the port used by the server.